//
//  ARTAvdioPlayer.m
//  ChartsDemo
//
//  Created by Kary on 2022/11/14.
//

#import "ARTAvdioPlayer.h"

static ARTAvdioPlayer *_instance;

@interface ARTAvdioPlayer ()

@property (strong, nonatomic) AVAudioPlayer *audioPlayer;
@property (nonatomic, strong) AVPlayerItem *playerItem;

@end

@implementation ARTAvdioPlayer
+ (instancetype)shareInstance {
    static ARTAvdioPlayer *_instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}

- (void)playAvdioWithUrl:(NSString *)audioPath{
    NSError *error = nil;
    if (audioPath.length) {
        if (_audioPlayer) {
            if (_audioPlayer.playing) {
                [_audioPlayer stop];
            }
            _audioPlayer = nil;
        }
        NSURL *url = [NSURL fileURLWithPath:audioPath];
        _audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
        if (!error) {
            _audioPlayer.volume = 1.0;
            [_audioPlayer prepareToPlay];
            [_audioPlayer play];
        }else{
            NSLog(@"audio play error=%@",error);
        }
    }
}

- (void)continuePlay{
    [_playerItem seekToTime:kCMTimeZero];
    [_audioPlayer play];
}

- (void)pausePlayer{
    [_audioPlayer pause];
}

- (void)restartAudioSession {
    [_audioPlayer play];
}

- (void)destroyPlayer{
    [_audioPlayer pause];
    [_playerItem cancelPendingSeeks];
    [_playerItem.asset cancelLoading];
    _playerItem = nil;
    _audioPlayer = nil;
}

- (void)changeAudioSessionCategory:(AVAudioSessionCategory)audioSessionCategory{
    NSError *error;
    [[AVAudioSession sharedInstance] setCategory:audioSessionCategory error:&error];
    if (error) {
        [self destroyPlayer];
        NSLog(@"音频设置播放模式失败失败");
    }
}

- (void)dealloc{
    [self destroyPlayer];
}


@end
